package com.ce.common.db.execution.impl;

import com.ce.common.db.base.Database;
import com.ce.common.db.execution.SQLFileExecution;

/**
 * 用于执行sql文件的具体实现类, 在windows操作系统下可以运行, Linux系统有待验证
 * @author yangenxiong
 *
 */
public class MySQLFileExecution implements SQLFileExecution {

	private Database database;

	public MySQLFileExecution(Database database) {
		this.database = database;
	}

	/**
	 * 执行单个sql文件(windows下)
	 * @author yangenxiong
	 * @param filePath sql文件的路径
	 */
	public boolean executeFile(String filePath) {
		String userName = database.getUser();
		String pass = database.getPass();
		String host = database.getHost();
		String databaseName = database.getDatabaseName();
		try {
			StringBuffer sb = new StringBuffer();
			sb.append("cmd /c mysql -u" + userName);
			sb.append(" -p" + pass);
			sb.append(" -h" + host);
			sb.append(" " + databaseName + " < ");
			sb.append(filePath);
			Process process = java.lang.Runtime.getRuntime().exec(sb.toString());
			process.waitFor();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 执行单个sql文件(Linux下)
	 * @author 胡煦
	 * @param filePath sql文件的路径
	 */
	public boolean executeFileInLinux(String filePath) {
		String userName = database.getUser();
		String pass = database.getPass();
		String host = database.getHost();
		String databaseName = database.getDatabaseName();
		try {
			StringBuffer sb = new StringBuffer();
			sb.append("mysql -u" + userName);
			sb.append(" -p" + pass);
			sb.append(" -h" + host);
			sb.append(" " + databaseName + " < ");
			sb.append(filePath);
			Process process = java.lang.Runtime.getRuntime().exec(sb.toString());
			process.waitFor();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 执行多个sql文件
	 * @author yangenxiong
	 * @param filePaths 多个sql文件的路径
	 * @return true 所有文件执行成功  false 其中有一份或者多份执行失败
	 */
	public boolean executeFiles(String[] filePaths) {
		boolean result = true;
		for (int i = 0; i < filePaths.length; i++) {
			boolean flag = executeFile(filePaths[i]);
			if (flag == false) {
				result = flag;//如果有一个文件执行失败, 则最后返回false
			}
		}
		return result;
	}
}
